package com.generalaj.console.configuration.workflow;


import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.util.*;

/**
 * Created by wangxin on 2017/2/27.
 */
public class GraphParser {

    private GraphNode root;
    private GraphManager maker;

    public void parseGraphConfig(File path) throws IOException {
        String initJobType="init";
        String initJobName="init_workspace";
        maker=new GraphManager();
        GraphConfig gconfig=getGraphConfig(path);
        GraphNode root=maker.createRootNode();
        GraphNode initWorkspace=maker.addNext(root,initJobType,initJobName);
        GraphNode last=initWorkspace;
        Iterator<Job> jobIterator=gconfig.getJobs().iterator();
        while (jobIterator.hasNext()) {
            Job job=jobIterator.next();
            GraphNode currentNode=maker.addNext(last,job.getType(),job.getName());
            for(Map.Entry<String,String> entry:job.getConfiguration().entrySet()){
                currentNode.updateConfig(entry.getKey(),entry.getValue());
            }
            last=currentNode;
        }
        this.root=root;
    }

    public GraphConfig getGraphConfig(File path) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        GraphConfig config=objectMapper.readValue(path,GraphConfig.class);
        return config;
    }

    public Set<GraphNode> getAllNodes(){
        return maker.getAllNodes();
    }

    public GraphManager getMaker() {
        return maker;
    }

}
